<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="盘点名称" prop="shelfName">
        <el-input
          v-model="queryParams.shelfName"
          placeholder="请输入盘点名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点单号" prop="shelfNumber">
        <el-input
          v-model="queryParams.shelfNumber"
          placeholder="请输入盘点单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实物盘点时间" prop="shelfDate">
        <el-date-picker clearable size="small"
          v-model="queryParams.shelfDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择实物盘点时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="仓库名称" prop="storeName">
        <storehouse-input
            ref="storehouseParams"
            :storehouse-props.sync="storehouseData"
            v-model="form.storeName"
          />
      </el-form-item>
      <el-form-item label="盘点状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择盘点状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supplier:storeShelf:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supplier:storeShelf:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supplier:storeShelf:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supplier:storeShelf:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeShelfList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="盘点名称" align="center" prop="shelfName" />
      <el-table-column label="盘点单号" align="center" prop="shelfNumber" />
      <el-table-column label="实物盘点时间" align="center" prop="shelfDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.shelfDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库名称" align="center" prop="storeName" />
      <el-table-column label="门店类型" align="center" prop="sName" />
      <el-table-column label="盘点状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['supplier:storeShelf:edit']"
            v-show="scope.row.status === 0"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supplier:storeShelf:remove']"
            v-show="scope.row.status === 0"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['supplier:storeShelf:view']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存盘点对话框 -->
    <el-dialog :title="title" :visible.sync="open" :fullscreen="true" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px"> 
        <el-form-item label="盘点单号" prop="shelfNumber">
          <el-input v-model="form.shelfNumber" placeholder="请输入盘点单号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="盘点名称" prop="shelfName">
          <el-input v-model="form.shelfName" placeholder="请输入盘点名称"  :disabled="showView"/>
        </el-form-item>
        <el-form-item label="实物盘点时间" prop="shelfDate">
          <el-date-picker clearable size="small"
            v-model="form.shelfDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择实物盘点时间" :disabled="showView">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仓库名称" prop="storeName">
          <storehouse-input
            ref="storehouseParams"
            :storehouse-props.sync="storehouseData"
            v-model="form.storeName"
          />
        </el-form-item>
        <el-form-item label="门店类型" prop="sId">
          <el-select v-model="form.sId" :disabled="showView" placeholder="请选择门店类型">
            <el-option
              v-for="dict in storeListOptions"
              :key="dict.id"
              :label="dict.name"
              :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盘点状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择盘点状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">库存盘点明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTbStoreShelfDetail" v-show="!showView">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteTbStoreShelfDetail" v-show="!showView">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="tbStoreShelfDetailList" :row-class-name="rowTbStoreShelfDetailIndex" @selection-change="handleTbStoreShelfDetailSelectionChange" ref="tbStoreShelfDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商品分类" prop="typeName" />
          <el-table-column label="商品名称" prop="productName" />
          <el-table-column label="生产日期" prop="productDate" />
          <el-table-column label="规格" prop="itemName" />
          <el-table-column label="当前库存数量" prop="storeCount" />
          <el-table-column label="实物盘点数量" prop="physicalAssets" min-width="100px">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.physicalAssets" :step="1" size="mini"
                step-strictly controls-position="right"  @change="handleQtyChange(scope.row)"
                :min="1" placeholder="请输入实物盘点数量" />
            </template>
          </el-table-column>
          <el-table-column label="实物盘点差异" prop="physicalDifference" />
          <el-table-column label="实物盘点结果" prop="physicalResult" :formatter="physicalResultFormat" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(0)" v-show="!showView">保 存</el-button>
        <el-button type="success" @click="submitForm(1)" v-show="!showView">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--选中商品组件-->
    <product-dialog
      :product-props.sync="productData"
      :handle-select="handleSelect"
      ref="productParams"
    />
  </div>
</template>

<script>
import { listStoreShelf, getStoreShelf, delStoreShelf, addStoreShelf, updateStoreShelf, exportStoreShelf,generateNumber } from "@/api/supplier/storeShelf";
import storehouseInput from "@/views/supplier/storehouse/input";
import productDialog from "@/views/supplier/product/dialog";
import { listStore } from "@/api/supplier/store";
export default {
  name: "StoreShelf",
  components: {
    storehouseInput,productDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbStoreShelfDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存盘点表格数据
      storeShelfList: [],
      // 库存盘点明细表格数据
      tbStoreShelfDetailList: [],
      //门店类型
      storeListOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查看标识
      showView: false,
      // 盘点状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shelfName: null,
        shelfNumber: null,
        shelfDate: null,
        storeId: null,
        status: null,
        orderByColumn: "id",
        isAsc: "desc"
      },
      // 实物盘点结果字典
      physicalResultOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
         shelfDate: [
          { required: true, message: "实物盘点时间不能为空", trigger: "change" }
        ],
        sId: [
          { required: true, message: "门店类型不能为空", trigger: "change" }
        ], 
        storeName:[
          { required: true, message: "仓库名称不能为空", trigger: "change" }
        ],

        
      },
      storehouseData: {
        id: null,
        storeName: null,
      },
      productData: {
        open: false,
        currentQtyShow: true,
        productList: [],
        //隐藏单价
        priceShow: false,
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("bus_store_shelf_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("bus_check_result").then(response => {
      this.physicalResultOptions = response.data;
    });
    this.getListStore();
  },
  methods: {
    /** 查询库存盘点列表 */
    getList() {
      this.loading = true;
      listStoreShelf(this.queryParams).then(response => {
        this.storeShelfList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getListStore(){
      listStore(null).then((response) =>{
        this.storeListOptions = response.rows;
      });
    },
    // 盘点状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 实物盘点结果字典翻译
    physicalResultFormat(row, column) {
      return this.selectDictLabel(this.physicalResultOptions, row.physicalResult);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shelfName: null,
        shelfNumber: null,
        shelfDate: null,
        storeId: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.tbStoreShelfDetailList = [];
       
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {

      this.single = selection.length!==1
      this.multiple = !selection.length
      this.ids = selection.map(item =>
      {
        if(item.status>0){
           this.multiple=true;
        }
        return item.id
      });

    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.shelfDate=new Date();
      this.open = true;
      this.showView=false;
      this.$refs.productParams.queryParams.ids=[];
      this.storehouseData.storeName = null;
      this.$refs.storehouseParams.scName =  null;
      this.form.status=0;
      this.title = "添加库存盘点";
      generateNumber().then((response) => {
          this.form.shelfNumber = response.msg;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.showView=false;
      const id = row.id || this.ids
      getStoreShelf(id).then(response => {

        this.form = response.data;
        console.log(this.form)
        if(this.form.status!=0){
          this.msgError("已提交数据，不能修改!");
          return;
        }
        generateNumber().then((response) => {
          this.form.shelfNumber = response.msg;
        });
        this.tbStoreShelfDetailList = response.data.tbStoreShelfDetailList;
        this.storehouseData.storeName = this.form.storeName;
        this.open = true;
        this.title = "修改库存盘点";
      });
    },
    /** 提交按钮 */
    submitForm(status) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.tbStoreShelfDetailList = this.tbStoreShelfDetailList;
          this.form.storeId = this.storehouseData.id;
          this.form.status=status;
          if (this.form.id != null) {
            updateStoreShelf(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStoreShelf(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除库存盘点编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStoreShelf(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
	/** 库存盘点明细序号 */
    rowTbStoreShelfDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 库存盘点明细添加按钮操作 */
    handleAddTbStoreShelfDetail() {
      
      if(this.storehouseData.id==null || this.form.sId==null){
        this.msgError("请选择仓库和门店类型");
        return;
      }
      
      if (this.tbStoreShelfDetailList.length > 0) {
        this.tbStoreShelfDetailList.map((item) => {
          var index = this.$refs.productParams.queryParams.ids.findIndex(
            function (value) {
              return (value = item.priceId);
            }
          );
          if (index == -1) {
            this.$refs.productParams.queryParams.ids.push(item.priceId);
          }
        });
      }
      this.$refs.productParams.queryParams.storeId=this.storehouseData.id;
      this.$refs.productParams.queryParams.sId=this.form.sId;

      this.$refs.productParams.open = true;
      this.$refs.productParams.getProductList();
    },
    /** 库存盘点明细删除按钮操作 */
    handleDeleteTbStoreShelfDetail() {
      

      if (this.checkedTbStoreShelfDetail.length == 0) {
        this.$alert("请先选择要删除的库存盘点明细数据", "提示", { confirmButtonText: "确定", });
      } else {


        this.checkedTbStoreShelfDetail.forEach((item) => {
          for (let i = 0; i < this.tbStoreShelfDetailList.length; i++) {
            if (this.tbStoreShelfDetailList[i].id == item.id) {
              this.tbStoreShelfDetailList.splice(i, 1);
              this.$refs.productParams.queryParams.ids.splice(i, 1);
              this.$refs.productParams.productList.push(item);
              break;
            }
          }
        });

        this.checkedTbStoreShelfDetail = [];

      }
    },
    /** 单选框选中数据 */
    handleTbStoreShelfDetailSelectionChange(selection) {

        this.checkedTbStoreShelfDetail = selection;

    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有库存盘点数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStoreShelf(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids;
      getStoreShelf(id).then((response) => {
        this.form = response.data;
        if (
          response.data.tbStoreShelfDetailList != null &&
          response.data.tbStoreShelfDetailList[0].id != null
        ) {
          this.tbStoreShelfDetailList = response.data.tbStoreShelfDetailList;
        }
        this.showView = true;
        this.storehouseData.storeName = this.form.storeName;
        this.open = true;
        this.title = "查看库存盘点";
      });
    },
    handleSelect(data) {
      data.forEach((item) => {
        this.tbStoreShelfDetailList.push(item);

      });

    },
    handleQtyChange(row) {
      console.log(row)
      row.physicalDifference =this.$math.subtract(row.physicalAssets,row.storeCount);
      if(row.physicalDifference>0){
        row.physicalResult=2;
      }else if(row.physicalDifference==0){
        row.physicalResult=0;
      }else{
        row.physicalResult=1;
      }

    },

  }
};
</script>
